<template>
  <div class="guides-page">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面头部 -->
      <div class="page-header flex justify-between items-center mb-8">
        <div>
          <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            寻找攻略
          </h1>
          <p class="text-gray-600 dark:text-gray-400">
            发现精彩旅游攻略，让您的旅程更加完美
          </p>
        </div>
        <div class="flex items-center gap-3">
          <el-button
            type="primary"
            size="large"
            class="flex items-center !h-[44px] !px-6"
            @click="$router.push('/user/guides')"
          >
            <el-icon class="mr-2 text-xl"><Document /></el-icon>
            我发表的攻略
          </el-button>
          <el-button
            type="primary"
            size="large"
            class="flex items-center !h-[44px] !px-6"
            @click="showPublishDialog = true"
          >
            <el-icon class="mr-2 text-xl"><Edit /></el-icon>
            发布攻略
          </el-button>
          <el-button
            type="primary"
            size="large"
            class="flex items-center !h-[44px] !px-6"
            @click="$router.push('/ai-guide')"
          >
            <el-icon class="mr-2 text-xl"><Cpu /></el-icon>
            AI智能攻略
          </el-button>
        </div>
      </div>

      <!-- 发布攻略弹窗 -->
      <el-dialog
        v-model="showPublishDialog"
        title="发布攻略"
        width="800px"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        :append-to-body="true"
        class="publish-dialog"
        :modal-class="'dialog-modal'"
      >
        <div class="dialog-header mb-6">
          <p class="text-sm text-gray-500 dark:text-gray-400">
            分享你的贵港旅行体验，记录精彩瞬间，为其他游客提供宝贵的参考建议
          </p>
        </div>

        <el-form
          ref="publishFormRef"
          :model="publishForm"
          :rules="publishRules"
          label-width="100px"
          class="publish-form overflow-y-auto max-h-[calc(100vh-300px)]"
        >
          <!-- 攻略标题 -->
          <el-form-item label="攻略标题" prop="title">
            <el-input
              v-model="publishForm.title"
              placeholder="给你的攻略起个吸引人的标题吧"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <!-- 封面图片 -->
          <el-form-item label="封面图片" prop="cover">
            <el-upload
              class="cover-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleCoverSuccess"
              :before-upload="beforeCoverUpload"
            >
              <el-image
                v-if="publishForm.cover"
                :src="publishForm.cover"
                class="w-full h-48 object-cover rounded"
              />
              <div v-else class="upload-placeholder">
                <el-icon class="text-3xl"><Picture /></el-icon>
                <div class="mt-2">上传一张精美的封面照片</div>
                <div class="mt-1 text-xs text-gray-500">
                  建议尺寸 1920x1080，支持 jpg/png 格式
                </div>
              </div>
            </el-upload>
          </el-form-item>

          <!-- 攻略简介 -->
          <el-form-item label="攻略简介" prop="description">
            <el-input
              v-model="publishForm.description"
              type="textarea"
              :rows="3"
              placeholder="简单介绍一下这篇攻略的特色和亮点"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <!-- 游玩天数 -->
          <el-form-item label="游玩天数" prop="days">
            <div class="flex items-center">
              <el-input-number v-model="publishForm.days" :min="1" :max="7" />
              <span class="ml-2 text-gray-500 text-sm">天</span>
            </div>
          </el-form-item>

          <!-- 相关景点 -->
          <el-form-item label="相关景点" prop="spots">
            <el-select
              v-model="publishForm.spots"
              multiple
              filterable
              placeholder="选择你去过的景点"
              style="width: 100%"
            >
              <el-option
                v-for="spot in spots"
                :key="spot.value"
                :label="spot.label"
                :value="spot.value"
              />
            </el-select>
          </el-form-item>

          <!-- 攻略标签 -->
          <el-form-item label="攻略标签" prop="tags">
            <el-select
              v-model="publishForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="添加标签，让别人更容易找到你的攻略"
              style="width: 100%"
            >
              <el-option
                v-for="tag in hotTags"
                :key="tag.name"
                :label="tag.name"
                :value="tag.name"
              />
            </el-select>
            <div class="mt-2 text-xs text-gray-500">
              推荐标签：
              <el-tag
                v-for="tag in hotTags.slice(0, 5)"
                :key="tag.name"
                size="small"
                class="mr-1 cursor-pointer"
                @click="addTag(tag.name)"
              >
                {{ tag.name }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 攻略内容 -->
          <el-form-item label="攻略内容" prop="content">
            <div
              class="border dark:border-gray-700 rounded-lg p-6 space-y-6 bg-gray-50 dark:bg-gray-800"
            >
              <div
                v-for="(day, index) in publishForm.content"
                :key="index"
                class="day-content space-y-4"
              >
                <div class="flex items-center justify-between">
                  <h3 class="text-lg font-medium flex items-center">
                    <span
                      class="mr-2 w-6 h-6 bg-primary-100 dark:bg-primary-900 text-primary-600 dark:text-primary-400 rounded-full flex items-center justify-center text-sm"
                    >
                      {{ index + 1 }}
                    </span>
                    第{{ index + 1 }}天
                  </h3>
                  <el-button
                    v-if="index === publishForm.content.length - 1"
                    type="primary"
                    link
                    @click="addDay"
                  >
                    <el-icon class="mr-1"><Plus /></el-icon>
                    添加下一天
                  </el-button>
                </div>

                <!-- 当天标题 -->
                <el-input
                  v-model="day.title"
                  placeholder="请输入当天主题"
                  class="mb-4"
                />

                <!-- 景点列表 -->
                <div
                  v-for="(spot, spotIndex) in day.spots"
                  :key="spotIndex"
                  class="spot-item bg-gray-50 dark:bg-gray-700 rounded p-4 mb-4"
                >
                  <div class="flex justify-between items-center mb-4">
                    <h4 class="text-base font-medium">
                      景点 {{ spotIndex + 1 }}
                    </h4>
                    <el-button
                      type="danger"
                      link
                      @click="removeSpot(index, spotIndex)"
                    >
                      删除景点
                    </el-button>
                  </div>

                  <el-form-item label="景点名称">
                    <el-input
                      v-model="spot.name"
                      placeholder="请输入景点名称"
                    />
                  </el-form-item>

                  <el-form-item label="游玩时间">
                    <el-time-picker
                      v-model="spot.startTime"
                      format="HH:mm"
                      placeholder="开始时间"
                      class="mr-2"
                    />
                    <el-time-picker
                      v-model="spot.endTime"
                      format="HH:mm"
                      placeholder="结束时间"
                    />
                  </el-form-item>

                  <el-form-item label="景点介绍">
                    <el-input
                      v-model="spot.description"
                      type="textarea"
                      :rows="2"
                      placeholder="请描述景点特色和游玩建议"
                    />
                  </el-form-item>

                  <el-form-item label="景点图片">
                    <el-upload
                      action="/api/upload"
                      list-type="picture-card"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handlePictureRemove"
                      :on-success="
                        (res) => handlePictureSuccess(res, index, spotIndex)
                      "
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                  </el-form-item>

                  <el-form-item label="小贴士">
                    <el-input
                      v-model="spot.tips"
                      placeholder="请输入游玩小贴士"
                    />
                  </el-form-item>

                  <el-form-item label="交通建议">
                    <el-input
                      v-model="spot.transportation"
                      placeholder="请输入交通建议"
                    />
                  </el-form-item>
                </div>

                <div class="flex justify-center">
                  <el-button type="primary" link @click="addSpot(index)">
                    添加景点
                  </el-button>
                </div>
              </div>
            </div>
          </el-form-item>

          <!-- 注意事项 -->
          <el-form-item label="注意事项">
            <div class="space-y-2">
              <div
                v-for="(note, index) in publishForm.notes"
                :key="index"
                class="flex items-center gap-2"
              >
                <el-input
                  v-model="note.title"
                  placeholder="标题"
                  style="width: 150px"
                />
                <el-input v-model="note.content" placeholder="内容" />
                <el-button type="danger" link @click="removeNote(index)">
                  删除
                </el-button>
              </div>
              <el-button type="primary" link @click="addNote">
                添加注意事项
              </el-button>
            </div>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showPublishDialog = false">取消</el-button>
            <el-button
              type="primary"
              @click="submitPublish"
              :loading="publishing"
            >
              {{ publishing ? "发布中..." : "发布攻略" }}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 图片预览弹窗 -->
      <el-dialog v-model="showPreviewDialog">
        <el-image
          style="width: 100%"
          :src="previewUrl"
          :preview-src-list="[previewUrl]"
        />
      </el-dialog>

      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 筛选区域 -->
          <div
            class="filter-section bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-8"
          >
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
              <el-input
                v-model="filters.keyword"
                placeholder="搜索攻略"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-select
                v-model="filters.type"
                placeholder="攻略类型"
                clearable
              >
                <el-option
                  v-for="type in types"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
              <el-select
                v-model="filters.spot"
                placeholder="相关景点"
                clearable
              >
                <el-option
                  v-for="spot in spots"
                  :key="spot.value"
                  :label="spot.label"
                  :value="spot.value"
                />
              </el-select>
              <el-select v-model="filters.sort" placeholder="排序方式">
                <el-option
                  v-for="sort in sorts"
                  :key="sort.value"
                  :label="sort.label"
                  :value="sort.value"
                />
              </el-select>
            </div>
          </div>

          <!-- 攻略列表 -->
          <div class="guides-grid space-y-6" v-loading="loading">
            <div
              v-for="guide in guides"
              :key="guide.id"
              class="guide-card bg-white dark:bg-gray-800 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-all duration-300 cursor-pointer"
              @click="
                $router.push({
                  name: 'TravelGuideDetail',
                  params: { id: guide.id },
                })
              "
            >
              <div class="flex h-64 md:h-56">
                <div class="w-1/3 relative">
                  <el-image
                    :src="guide.cover"
                    class="w-full h-full object-cover"
                    fit="cover"
                  >
                    <template #error>
                      <div class="image-placeholder flex items-center justify-center h-full bg-gray-100 dark:bg-gray-700">
                        <el-icon class="text-4xl text-gray-400"><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div class="absolute top-3 right-3">
                    <el-button
                      circle
                      class="!w-9 !h-9"
                      :class="{ 'is-favorite': guide.isFavorite }"
                      @click.stop="toggleFavorite(guide)"
                    >
                      <el-icon class="text-lg"><Star /></el-icon>
                    </el-button>
                  </div>
                </div>
                <div class="w-2/3 p-6 flex flex-col justify-between">
                  <div>
                    <div class="flex items-center gap-2 mb-3">
                      <el-tag
                        :type="guide.type === 'official' ? 'success' : 'warning'"
                        size="small"
                      >
                        {{ guide.type === "official" ? "官方" : "用户" }}
                      </el-tag>
                      <el-tag v-if="guide.isHot" type="danger" size="small"
                        >热门</el-tag
                      >
                      <span class="text-sm text-gray-500 ml-auto">{{
                        formatTime(guide.date)
                      }}</span>
                    </div>
                    <h3
                      class="text-xl font-medium text-gray-900 dark:text-white mb-3 line-clamp-1"
                    >
                      {{ guide.title }}
                    </h3>
                    <p
                      class="text-gray-600 dark:text-gray-400 text-sm mb-5 line-clamp-1"
                    >
                      {{ guide.description }}
                    </p>
                  </div>
                  <div>
                    <div class="flex items-center justify-between mb-4">
                      <div class="flex items-center">
                        <el-avatar
                          :size="28"
                          :src="guide.author.avatar"
                          class="mr-2"
                        />
                        <span class="text-sm text-gray-600 dark:text-gray-400">
                          {{ guide.author.name }}
                        </span>
                      </div>
                      <div class="flex items-center gap-4 text-sm text-gray-500">
                        <span class="flex items-center">
                          <el-icon class="mr-1"><View /></el-icon>
                          {{ formatNumber(guide.views) }}
                        </span>
                        <span class="flex items-center">
                          <el-icon class="mr-1"><Star /></el-icon>
                          {{ formatNumber(guide.likes) }}
                        </span>
                        <span class="flex items-center">
                          <el-icon class="mr-1"><ChatDotRound /></el-icon>
                          {{ formatNumber(guide.comments) }}
                        </span>
                      </div>
                    </div>
                    <div class="flex flex-wrap gap-2">
                      <el-tag
                        v-for="tag in guide.tags"
                        :key="tag"
                        size="small"
                        effect="plain"
                      >
                        {{ tag }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty
              v-if="!loading && !guides.length"
              description="暂无相关攻略"
            >
              <el-button type="primary" @click="resetFilters"
                >清除筛选</el-button
              >
            </el-empty>
          </div>

          <!-- 分页 -->
          <div class="pagination-section flex justify-center mt-8">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 30, 40]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 热门攻略 -->
          <div
            class="hot-guides bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Star /></el-icon>
              热门攻略
            </h3>
            <div class="space-y-4">
              <div
                v-for="guide in hotGuides"
                :key="guide.id"
                class="hot-guide-item group cursor-pointer"
                @click="
                  $router.push({
                    name: 'TravelGuideDetail',
                    params: { id: guide.id },
                  })
                "
              >
                <div class="relative rounded-lg overflow-hidden mb-2">
                  <el-image
                    :src="guide.cover"
                    class="w-full h-32 object-cover group-hover:scale-105 transition-transform duration-300"
                  />
                  <div
                    class="absolute inset-0 bg-black/30 group-hover:bg-black/10 transition-colors"
                  ></div>
                </div>
                <h4
                  class="text-sm font-medium text-gray-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 line-clamp-2 mb-2"
                >
                  {{ guide.title }}
                </h4>
                <div
                  class="flex items-center justify-between text-xs text-gray-500"
                >
                  <span class="flex items-center">
                    <el-icon class="mr-1"><View /></el-icon>
                    {{ formatNumber(guide.views) }}
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Star /></el-icon>
                    {{ formatNumber(guide.likes) }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 热门标签 -->
          <div
            class="hot-tags bg-white dark:bg-gray-800 rounded-lg shadow-md p-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Collection /></el-icon>
              热门标签
            </h3>
            <div class="flex flex-wrap gap-2">
              <el-tag
                v-for="tag in hotTags"
                :key="tag.name"
                :type="tag.type"
                effect="light"
                class="cursor-pointer"
                @click="handleTagClick(tag)"
              >
                {{ tag.name }}
                <span class="ml-1 text-xs opacity-75">({{ tag.count }})</span>
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Magic,
  View,
  Star,
  Search,
  Picture,
  ChatDotRound,
  Collection,
  Cpu,
  Edit,
  Plus,
  Document,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import axios from "@/api/axios";
// 导入测试数据
import { guideData, hotTags as mockHotTags, filterOptions } from "@/mock/guideData";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const route = useRoute();
const loading = ref(false);

// 筛选选项
const types = filterOptions.types;

// 景点数据
const spots = ref(filterOptions.spots);

const sorts = filterOptions.sorts;

// 筛选条件
const filters = reactive({
  keyword: "",
  type: "",
  spot: "",
  sort: "latest",
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 攻略数据
const guides = ref([]);
// 所有攻略数据（未分页）
const allGuides = ref([]);

// 热门攻略
const hotGuides = ref([]);

// 热门标签
const hotTags = ref(mockHotTags);

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 加载景点数据
const loadSpots = async () => {
  try {
    const response = await axios.get("/api/public/spots");
    if (response.data && response.data.code === 200) {
      spots.value = response.data.data;
    } else {
      // 使用测试数据
      spots.value = filterOptions.spots;
    }
  } catch (error) {
    console.error("加载景点数据失败:", error);
    // 使用测试数据
    spots.value = filterOptions.spots;
  }
};

// 加载热门标签
const loadHotTags = async () => {
  try {
    const response = await axios.get("/api/public/tags/hot");
    if (response.data && response.data.code === 200) {
      hotTags.value = response.data.data;
    } else {
      // 使用测试数据
      hotTags.value = mockHotTags;
    }
  } catch (error) {
    console.error("加载热门标签失败:", error);
    // 使用测试数据
    hotTags.value = mockHotTags;
  }
};

// 加载热门攻略
const loadHotGuides = async () => {
  try {
    const response = await axios.get("/api/public/guides/hot");
    if (response.data && response.data.code === 200) {
      hotGuides.value = response.data.data;
    } else {
      // 使用测试数据
      hotGuides.value = guideData.slice(0, 3).map(guide => ({
        id: guide.id,
        title: guide.title,
        cover: guide.cover,
        views: guide.views,
        likes: guide.likes
      }));
    }
  } catch (error) {
    console.error("加载热门攻略失败:", error);
    // 使用测试数据
    hotGuides.value = guideData.slice(0, 3).map(guide => ({
      id: guide.id,
      title: guide.title,
      cover: guide.cover,
      views: guide.views,
      likes: guide.likes
    }));
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  filterAndPaginateGuides();
};

// 重置筛选
const resetFilters = () => {
  Object.assign(filters, {
    keyword: "",
    type: "",
    spot: "",
    sort: "latest",
  });
  currentPage.value = 1;
  filterAndPaginateGuides();
};

// 处理收藏
const toggleFavorite = async (guide) => {
  try {
    // 如果用户未登录，提示登录
    const token = localStorage.getItem("token");
    if (!token) {
      ElMessage.warning("请先登录");
      return;
    }

    await axios.post(`/api/user/guides/favorite/${guide.id}`, {
      isFavorite: !guide.isFavorite
    });
    
    guide.isFavorite = !guide.isFavorite;
    ElMessage.success(guide.isFavorite ? "收藏成功" : "已取消收藏");
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理标签点击
const handleTagClick = (tag) => {
  filters.keyword = tag.name;
  currentPage.value = 1;
  filterAndPaginateGuides();
};

// 从API加载攻略数据
const loadGuidesFromApi = async () => {
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: filters.keyword,
      type: filters.type,
      spot: filters.spot,
      sort: filters.sort
    };

    const response = await axios.get("/api/public/guides", { params });
    if (response.data && response.data.code === 200) {
      guides.value = response.data.data.records;
      total.value = response.data.data.total;
      loading.value = false;
      return true;
    }
    return false;
  } catch (error) {
    console.error("从API加载攻略失败:", error);
    return false;
  }
};

// 从Mock数据加载攻略
const loadGuidesFromMock = () => {
  // 复制整个数据集以避免修改原始数据
  allGuides.value = JSON.parse(JSON.stringify(guideData));
  filterAndPaginateGuides();
};

// 过滤和分页攻略数据
const filterAndPaginateGuides = () => {
  let filteredGuides = [...allGuides.value];
  
  // 关键词筛选
  if (filters.keyword.trim()) {
    const keyword = filters.keyword.toLowerCase();
    filteredGuides = filteredGuides.filter(guide => 
      guide.title.toLowerCase().includes(keyword) || 
      guide.description.toLowerCase().includes(keyword) || 
      guide.tags.some(tag => tag.toLowerCase().includes(keyword))
    );
  }
  
  // 类型筛选
  if (filters.type) {
    filteredGuides = filteredGuides.filter(guide => guide.type === filters.type);
  }
  
  // 景点筛选
  if (filters.spot) {
    const spotLabel = spots.value.find(s => s.value === Number(filters.spot))?.label;
    if (spotLabel) {
      filteredGuides = filteredGuides.filter(guide => 
        guide.title.includes(spotLabel) || 
        guide.description.includes(spotLabel)
      );
    }
  }
  
  // 排序
  if (filters.sort === 'latest') {
    filteredGuides.sort((a, b) => {
      if (a.author.name === "贵港文旅" && b.author.name !== "贵港文旅") return -1;
      if (a.author.name !== "贵港文旅" && b.author.name === "贵港文旅") return 1;
      if (a.type === "official" && b.type !== "official") return -1;
      if (a.type !== "official" && b.type === "official") return 1;
      return new Date(b.date) - new Date(a.date);
    });
  } else if (filters.sort === 'views') {
    filteredGuides.sort((a, b) => {
      if (a.author.name === "贵港文旅" && b.author.name !== "贵港文旅") return -1;
      if (a.author.name !== "贵港文旅" && b.author.name === "贵港文旅") return 1;
      if (a.type === "official" && b.type !== "official") return -1;
      if (a.type !== "official" && b.type === "official") return 1;
      return b.views - a.views;
    });
  } else if (filters.sort === 'likes') {
    filteredGuides.sort((a, b) => {
      if (a.author.name === "贵港文旅" && b.author.name !== "贵港文旅") return -1;
      if (a.author.name !== "贵港文旅" && b.author.name === "贵港文旅") return 1;
      if (a.type === "official" && b.type !== "official") return -1;
      if (a.type !== "official" && b.type === "official") return 1;
      return b.likes - a.likes;
    });
  } else if (filters.sort === 'comments') {
    filteredGuides.sort((a, b) => {
      if (a.author.name === "贵港文旅" && b.author.name !== "贵港文旅") return -1;
      if (a.author.name !== "贵港文旅" && b.author.name === "贵港文旅") return 1;
      if (a.type === "official" && b.type !== "official") return -1;
      if (a.type !== "official" && b.type === "official") return 1;
      return b.comments - a.comments;
    });
  }
  
  // 更新总记录数
  total.value = filteredGuides.length;
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  guides.value = filteredGuides.slice(start, end);
};

// 加载攻略数据
const loadGuides = async () => {
  loading.value = true;
  try {
    const success = await loadGuidesFromApi();
    if (!success) {
      loadGuidesFromMock();
    }
  } catch (error) {
    console.error("加载攻略失败:", error);
    loadGuidesFromMock();
  } finally {
    loading.value = false;
  }
};

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  if (allGuides.value.length > 0) {
    filterAndPaginateGuides();
  } else {
    loadGuides();
  }
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  if (allGuides.value.length > 0) {
    filterAndPaginateGuides();
  } else {
    loadGuides();
  }
};

// 根据URL参数加载相关景点的攻略
onMounted(async () => {
  // 加载景点和标签数据
  await Promise.all([loadSpots(), loadHotTags(), loadHotGuides()]);
  
  const spotId = route.query.spotId;
  if (spotId) {
    filters.spot = spotId;
  }
  
  // 确保初始加载时默认排序为"latest"
  if (!filters.sort) {
    filters.sort = "latest";
  }
  
  // 加载攻略数据
  loadGuides();
});

// 发布攻略相关逻辑
const showPublishDialog = ref(false);
const publishFormRef = ref(null);
const publishForm = ref({
  title: "",
  cover: "",
  description: "",
  days: 1,
  spots: [],
  tags: [],
  content: [{ title: "", spots: [] }],
  notes: [],
});
const publishRules = {
  title: [{ required: true, message: "请输入攻略标题", trigger: "blur" }],
  cover: [{ required: true, message: "请上传封面图片", trigger: "blur" }],
  description: [{ required: true, message: "请输入攻略简介", trigger: "blur" }],
  days: [{ required: true, message: "请输入游玩天数", trigger: "blur" }],
  spots: [{ required: true, message: "请选择相关景点", trigger: "change" }],
  tags: [{ required: true, message: "请选择攻略标签", trigger: "change" }],
};
const publishing = ref(false);
const previewUrl = ref("");
const showPreviewDialog = ref(false);

const handleCoverSuccess = (res) => {
  publishForm.value.cover = res.url;
};

const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片");
  }
  return isImage;
};

const addDay = () => {
  publishForm.value.content.push({ title: "", spots: [] });
};

const removeSpot = (dayIndex, spotIndex) => {
  publishForm.value.content[dayIndex].spots.splice(spotIndex, 1);
};

const addSpot = (dayIndex) => {
  publishForm.value.content[dayIndex].spots.push({
    name: "",
    startTime: "",
    endTime: "",
    description: "",
    images: [],
    tips: "",
    transportation: "",
  });
};

const handlePictureCardPreview = (file) => {
  previewUrl.value = file.url;
  showPreviewDialog.value = true;
};

const handlePictureRemove = () => {
  // 实现图片移除逻辑
};

const handlePictureSuccess = (res, dayIndex, spotIndex) => {
  if (!publishForm.value.content[dayIndex].spots[spotIndex].images) {
    publishForm.value.content[dayIndex].spots[spotIndex].images = [];
  }
  publishForm.value.content[dayIndex].spots[spotIndex].images.push(res.url);
};

const addNote = () => {
  publishForm.value.notes.push({ title: "", content: "" });
};

const removeNote = (index) => {
  publishForm.value.notes.splice(index, 1);
};

// 添加标签
const addTag = (tagName) => {
  if (!publishForm.value.tags.includes(tagName)) {
    publishForm.value.tags.push(tagName);
  }
};

const submitPublish = async () => {
  try {
    publishing.value = true;
    // 表单验证
    await publishFormRef.value.validate();
    
    // 检查用户是否登录
    const token = localStorage.getItem("token");
    if (!token) {
      ElMessage.warning("请先登录");
      publishing.value = false;
      return;
    }

    // 提交表单
    const response = await axios.post("/api/user/guides", publishForm.value);
    
    if (response.data && response.data.code === 200) {
      ElMessage.success("攻略发布成功");
      showPublishDialog.value = false;
      
      // 刷新攻略列表
      loadGuides();
    } else {
      ElMessage.error(response.data.message || "发布失败");
    }
  } catch (error) {
    console.error("发布失败:", error);
    ElMessage.error("发布失败: " + (error.message || "未知错误"));
  } finally {
    publishing.value = false;
  }
};

// 在 script setup 部分添加 watch
const lockScroll = () => {
  document.body.style.overflow = "hidden";
};

const unlockScroll = () => {
  document.body.style.overflow = "";
};

watch(showPublishDialog, (val) => {
  if (val) {
    lockScroll();
  } else {
    unlockScroll();
  }
});
</script>

<style lang="scss" scoped>
.guides-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  :deep(.dialog-modal) {
    @apply overflow-hidden;
  }

  :deep(.publish-dialog) {
    .el-dialog {
      position: fixed !important;
      top: 50% !important;
      left: 50% !important;
      transform: translate(-50%, -50%) !important;
      margin: 0 !important;
      max-height: 90vh !important;
      display: flex !important;
      flex-direction: column !important;
      overflow: hidden !important;
    }

    .el-dialog__header {
      flex-shrink: 0 !important;
      padding: 20px 20px 0 !important;
    }

    .el-dialog__body {
      flex: 1 !important;
      overflow-y: auto !important;
      overflow-x: hidden !important;
      padding: 20px !important;
      margin: 0 !important;
    }

    .el-dialog__footer {
      flex-shrink: 0 !important;
      padding: 10px 20px 20px !important;
      border-top: 1px solid var(--el-border-color-lighter);
    }

    .el-overlay {
      position: fixed !important;
      top: 0 !important;
      right: 0 !important;
      bottom: 0 !important;
      left: 0 !important;
      overflow: hidden !important;
      background-color: rgba(0, 0, 0, 0.5) !important;
      z-index: 2000 !important;
    }
  }

  .image-placeholder {
    @apply flex items-center justify-center w-full h-full bg-gray-100 dark:bg-gray-700;

    .el-icon {
      @apply text-4xl text-gray-400 dark:text-gray-500;
    }
  }

  .guide-card {
    @apply transition-all duration-300;
    
    &:hover {
      @apply transform -translate-y-1;
    }
    
    .is-favorite {
      @apply text-red-500;
    }
  }

  .hot-guide-item {
    &:hover {
      .el-image {
        @apply transform scale-105;
      }
    }
  }

  .publish-dialog {
    .publish-form {
      @apply pr-4;

      &::-webkit-scrollbar {
        @apply w-2;
      }

      &::-webkit-scrollbar-track {
        @apply bg-gray-100 dark:bg-gray-700 rounded;
      }

      &::-webkit-scrollbar-thumb {
        @apply bg-gray-300 dark:bg-gray-600 rounded hover:bg-gray-400 dark:hover:bg-gray-500;
      }

      :deep(.el-form-item__label) {
        @apply font-medium text-gray-700 dark:text-gray-300;
      }

      :deep(.el-input__wrapper),
      :deep(.el-textarea__inner) {
        @apply transition-all duration-300;

        &:hover {
          @apply border-primary-500;
        }

        &:focus-within {
          @apply ring-2 ring-primary-500/20;
        }
      }

      .day-content {
        @apply relative;

        &:not(:last-child)::after {
          content: "";
          @apply absolute left-3 top-12 bottom-0 w-0.5 bg-gray-200 dark:bg-gray-700;
        }
      }

      .spot-item {
        @apply relative transition-all duration-300;

        &:hover {
          @apply shadow-md transform -translate-y-0.5;
        }
      }
    }
  }

  :deep(.el-input-number) {
    .el-input-number__decrease,
    .el-input-number__increase {
      @apply bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300;

      &:hover {
        @apply text-primary-500 dark:text-primary-400;
      }
    }

    .el-input__wrapper {
      @apply bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100;
    }
  }

  .card-header {
    @apply flex items-center justify-between;

    .header-actions {
      @apply flex items-center gap-4;
    }
  }
}

.upload-placeholder {
  @apply flex flex-col items-center justify-center w-full h-48 bg-gray-50 dark:bg-gray-700 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded cursor-pointer hover:border-primary-500 dark:hover:border-primary-500 transition-colors;
}

:deep(.el-upload) {
  @apply w-full;
}

.spot-item {
  :deep(.el-form-item__label) {
    @apply text-sm;
  }
}

.cover-uploader {
  :deep(.el-upload) {
    @apply w-full cursor-pointer;
  }
}
</style>
